<template>
  <PageWrapper title="娱乐书签">
    <div style="display: flex; justify-content: center">
      <a-input-search
        v-model:value="searchText"
        placeholder="请输入网站名称"
        style="width: 600px; margin-bottom: 16px"
        enter-button
        @search="onSearch"
        @change="onSearch"
      />
      <a-button type="primary" style="margin-left: 5px" @click="showDrawer">新增</a-button>
    </div>
    <div
      v-for="(item, index) in data"
      :key="index"
      :style="{ marginTop: index !== 0 ? '16px' : '0px' }"
    >
      <a-card style="cursor: pointer" :title="item.categoryName" v-if="item.urls.length">
        <template v-for="(i, idx) in item.urls" :key="idx">
          <a-card-grid style="width: 10%; text-align: center">
            <img v-if="i.favicon" :src="i.favicon" alt="链接" class="favicon" />
            <a :href="i.url" @click="(e) => jump(e, i.url)">
              {{ i.name }}
            </a>
            <div style="margin-top: 5px">
              <a style="padding: 0 5px" @click="(e) => editUrl(e, item, i)">编辑</a>
              <a style="padding: 0 5px" @click="(e) => deleteUrl(e, i)">删除</a>
            </div>
          </a-card-grid>
        </template>
      </a-card>
    </div>
    <a-drawer
      title="新增书签"
      :width="720"
      :open="open"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <a-form :model="form" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="收藏夹" name="name">
              <a-input v-model:value="form.categoryName" style="width: 100%" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="链接名称" name="urlName">
              <a-input
                v-model:value="form.urlName"
                style="width: 100%"
                placeholder="请输入链接名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="链接" name="url">
              <a-input v-model:value="form.url" style="width: 100%" placeholder="请输入链接地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="favicon" name="favicon">
              <a-input
                v-model:value="form.favicon"
                style="width: 100%"
                placeholder="请输入favicon地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #extra>
        <a-space>
          <a-button @click="onClose">取消</a-button>
          <a-button type="primary" @click="onSave">保存</a-button>
        </a-space>
      </template>
    </a-drawer>
    <contextHolder />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import axios from '@/utils/myHttp';
  import { debounce, get } from 'lodash-es';
  import type { Rule } from 'ant-design-vue/es/form';
  import { notification } from 'ant-design-vue';

  const [api, contextHolder] = notification.useNotification();

  const searchText = ref<string>('');
  const data = ref<WebsiteGroup[]>([]);
  const originData = ref<WebsiteGroup[]>([]);
  const form = reactive({
    id: '',
    categoryName: '娱乐夹',
    url: '',
    urlName: '',
    favicon: '',
  });
  const category = ref<string[]>([]);

  const rules: Record<string, Rule[]> = {
    categoryName: [{ required: true, message: '请选择收藏夹' }],
    url: [{ required: true, message: '请输入链接' }],
    urlName: [{ required: true, message: '请输入链接名称' }],
    favicon: [{ required: false, message: '请输入favicon地址' }],
  };

  const open = ref<boolean>(false);

  const getData = () => {
    axios.get(`/api/bookmarks?categoryName=娱乐夹`).then(
      (response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        // 原结构,response.data.data，这里去掉第一层的data
        const _response = get(response, 'data');
        if (_response.success) {
          data.value = _response.data;
          category.value = _response.data.map((item) => item.categoryName);
          console.log('🚀 ~ axios.get ~ category.value:', category.value);
          originData.value = JSON.parse(JSON.stringify(_response.data));
        } else {
          api.info({
            message: _response.code,
            description: _response.message,
            placement: 'topRight',
          });
        }
      },
      (error) => {
        api.info({
          message: error.code,
          description: error.message,
          placement: 'topRight',
        });
      },
    );
  };

  // 删除链接
  const deleteUrl = (e, item) => {
    console.log('🚀 ~ deleteUrl ~ item:', item);
    e.preventDefault();
    axios.delete(`/api/bookmarks/${item.id}`).then(
      (response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        // 原结构,response.data.data，这里去掉第一层的data
        const _response = get(response, 'data');
        if (_response.success) {
          getData();
        } else {
          api.info({
            message: _response.code,
            description: _response.message,
            placement: 'topRight',
          });
        }
      },
      (error) => {
        api.info({
          message: error.code,
          description: error.message,
          placement: 'topRight',
        });
      },
    );
  };

  const editUrl = (e, item, i) => {
    e.preventDefault();
    showDrawer({
      id: i.id,
      categoryName: item.categoryName,
      urlName: i.name,
      url: i.url,
      favicon: i.favicon,
    });
  };

  const showDrawer = (obj) => {
    form.id = obj?.id;
    form.categoryName = '娱乐夹';
    form.urlName = obj?.urlName;
    form.url = obj?.url;
    form.favicon = obj?.favicon;
    open.value = true;
  };

  const onClose = () => {
    open.value = false;
  };
  const onSave = () => {
    open.value = false;
    console.log('form.id', form.id);
    axios[form.id ? 'put' : 'post'](`/api/bookmarks/${form.id ? form.id : ''}`, form).then(
      (response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        // 原结构,response.data.data，这里去掉第一层的data
        const _response = get(response, 'data');
        if (_response.success) {
          getData();
        } else {
          api.info({
            message: _response.code,
            description: _response.message,
            placement: 'topRight',
          });
        }
      },
      (error) => {
        api.info({
          message: error.code,
          description: error.message,
          placement: 'topRight',
        });
      },
    );
  };

  interface WebsiteGroup {
    categoryName: string;
    categoryId: string;
    urls: Website[];
  }

  interface Website {
    url: string;
    name: string;
    favicon: string;
  }

  getData();

  const jump = (e, url) => {
    e.preventDefault();
    window.open(url, '_blank');
  };

  // 前端搜索功能
  const onSearch = () => {
    const fn = () => {
      if (searchText.value) {
        data.value.forEach((item) => {
          item.urls = item.urls.filter((i) => {
            // 转小写，再判断
            const lowerStr = i.name.toLowerCase();
            const lowerSearchStr = searchText.value.toLowerCase();
            return lowerStr.includes(lowerSearchStr);
          });
        });
      } else {
        console.log('无值', originData.value);
        data.value = JSON.parse(JSON.stringify(originData.value));
      }
    };
    debounce(fn, 500)();
  };
</script>
<style scoped>
  .favicon {
    width: 16px;
    margin-top: -4px;
    margin-right: 5px;
  }
</style>
